1029. 两地调度【中等】
1. 📝 题目描述
公司计划面试 2n 人。给你一个数组 costs,其中 costs[i] = [aCosti, bCosti]。第 i 人飞往 a 市的费用为 aCosti,飞往 b 市的费用为 bCosti。
返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达。
示例 1:
txt
输入:costs = [[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 a 市,费用为 10。
第二个人去 a 市,费用为 30。
第三个人去 b 市,费用为 50。
第四个人去 b 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
示例 2:
txt
输入:costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
输出:18591
2
2
示例 3:
txt
输入:costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
输出:30861
2
2
提示:
2 * n == costs.length2 <= costs.length <= 100costs.length为偶数1 <= aCosti, bCosti <= 1000
2. 🎯 s.1 - 贪心
js
/**
* @param {number[][]} costs
* @return {number}
*/
var twoCitySchedCost = function (costs) {
costs.sort((a, b) => a[0] - a[1] - (b[0] - b[1]))
const n = costs.length / 2
let total = 0
for (let i = 0; i < n; i++) total += costs[i][0]
for (let i = n; i < 2 * n; i++) total += costs[i][1]
return total
}1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- 时间复杂度:
,其中 是 costs 的长度 - 空间复杂度:
,排序的栈空间
算法思路:
- 按“去 a 市与去 b 市的费用差”
costs[i][0] - costs[i][1]升序排序 - 前半部分人去 a 市(差值小,去 a 更划算),后半部分人去 b 市